package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.controller.utils.R;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService BookService;

    /*查询全部*/
    @GetMapping
    public R getAll(){
        return new R(true,BookService.list());
    }

    /*保存*/
    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
        if(book.getName().equals("123"))throw new IOException();
        boolean flag=BookService.save(book);
        return new R(flag , flag ? "添加成功^_^" : "添加失败");
    }

    /*修改*/
    @PutMapping
    public R update(@RequestBody Book book){
        return new R(BookService.modify(book));
    }

    /*根据id删除*/
    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(BookService.delete(id));
    }

    /*根据id查询*/
    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        System.out.println("测试热部署呀");
        System.out.println("测试热部署呀");
        System.out.println("测试热部署呀");
        System.out.println("测试热部署呀");
        return new R(true,BookService.getById(id));
    }

    /*分页查询*/
    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize,Book book){

        System.out.println("参数=》"+book);

        IPage<Book> page=BookService.getPage(currentPage,pageSize,book);
        /*如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值*/
        if(currentPage > page.getPages()){
            page=BookService.getPage((int)page.getPages(),pageSize,book);
        }
        return new R(true,page);
    }
}
